package com.mimo.comet.event.listener;

import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.mimo.comet.config.LocalCometServerConfig;
import com.mimo.comet.user.service.IUserService;
import com.mimo.common.listener.IMessage;
import com.mimo.common.utils.JsonUtils;

/**
 * 物理连接变更需要维护本地会话的实际绑定关系
 * <p>
 * 用户重复登陆时，需要相互通知，以保证在整个集群中，一个用户，只能绑定在一台物理机上
 * 
 * @author Hongyu
 */
@Service
public class CometSessionListener implements IMessage {

  @Autowired
  private LocalCometServerConfig localCometServerConfig;

  @Autowired
  private RedisTemplate<String, String> redisTemplate;

  @Autowired
  private IUserService userService;

  @Override
  public void onMessage(String event) {
    SessionCreatedEvent evt = JsonUtils.parseJson(event, SessionCreatedEvent.class);
    if (!Objects.equals(evt.getApplicationId(), localCometServerConfig.getApplicationId())) {
      userService.unbinding(evt.getUserId(), null, evt.getDeviceId());
    }
  }

  @Override
  public void send(Object message) {
    Objects.requireNonNull(message);
    if (message instanceof String) {
      redisTemplate.convertAndSend(this.getTopic(), message);
    } else {
      redisTemplate.convertAndSend(this.getTopic(), JsonUtils.toJsonString(message));
    }
  }

  @Override
  public String getTopic() {
    return localCometServerConfig.getClusterChannel();
  }

}
